import { defineStore } from 'pinia'; 
import { clone, cloneDeep } from 'lodash'; 
import app from './app';
import { showAuthModal } from '@/cfsheep/hooks/useModal';
import UserApi from '@/cfsheep/api/cfUser';

// 默认用户信息
const defaultUserInfo = {
	avatar: "",
	avatarUrl: "",
	birthday: "",
	businessLicenseStatus: null,
	cfRole: null,
	createTime: "",
	driverLicenseStatus: null,
	email: "",
	id: "",
	idCardStatus: null,
	lastLoginTime: "",
	nickName: "",
	password: "",
	phone: "",
	roleEndTime: "",
	sex: null,
	sign: "",
	trueName: "",
	type: null,
	userName: ""
};
 
 
const user = defineStore({
  id: 'user',
  state: () => ({
    userInfo: clone(defaultUserInfo), // 用户信息
    isLogin: !!uni.getStorageSync('token'), // 登录状态
    lastUpdateTime: 0, // 上次更新时间
  }),

  actions: {
    // 获取用户信息
    async getInfo() {
      const { code, data } = await UserApi.getUserInfo();
 
      if (code !== 10002) {
        return;
      }
      this.userInfo = data;
      return Promise.resolve(data);
    },

  

     
    // 设置 token
    setToken(token = '', refreshToken = '',jwtToken='') {
      if (token === '') {
        this.isLogin = false;
        uni.removeStorageSync('token');
        uni.removeStorageSync('refresh-token');
		uni.removeStorageSync('jwtToken');
      } else {
        this.isLogin = true;
        uni.setStorageSync('token', token);
        uni.setStorageSync('refresh-token', refreshToken);
		uni.setStorageSync('jwtToken', jwtToken);
        this.loginAfter();
      }
      return this.isLogin;
    },

    // 更新用户相关信息 (手动限流，5 秒之内不刷新)
    async updateUserData() {
      if (!this.isLogin) {
        this.resetUserData();
        return;
      }
      // 防抖，5 秒之内不刷新
      const nowTime = new Date().getTime();
      if (this.lastUpdateTime + 5000 > nowTime) {
        return;
      }
      this.lastUpdateTime = nowTime;

      // 获取最新信息
      await this.getInfo();
      
      return this.userInfo;
    },

    // 重置用户默认数据
    resetUserData() {
      // 清空 token
      this.setToken();
      // 清空用户相关的缓存
      this.userInfo = clone(defaultUserInfo);
   
     
    },

    
    async loginAfter() {
      await this.updateUserData();  
   
    },

    // 登出系统
    async logout() {
      this.resetUserData();
      return !this.isLogin;
    }
  },
  persist: {
    enabled: true,
    strategies: [{
      key: 'user-store',
    }]
  },
});

export default user;
